package com.murong.ai.chat.domain.chatbot.deepseek;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.murong.ai.chat.domain.chatbot.ChatBotService;
import com.murong.ai.chat.domain.chatbot.deepseek.module.MsgElement;
import com.murong.ai.chat.domain.chatbot.deepseek.module.OpenAiRequest;
import com.murong.ai.chat.infrastructure.httprequest.HttpClientService;
import com.murong.ai.chat.infrastructure.httprequest.module.HttpHeader;
import lombok.NonNull;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Service("deepSeekCall")
@ConditionalOnProperty(name = "chat.bot.call.service", havingValue = "aliyuncs", matchIfMissing = false)
public class DeepSeekService extends HttpClientService <OpenAiRequest,String> implements ChatBotService {
    private OpenAiRequest openAiRequest;
    private Environment environment;
    private String chatModel;
    private String accessKey;

    public DeepSeekService(Environment environment){
        this.environment=environment;
        this.chatModel=environment.getProperty("chat.bot.aliyuncs.model");
        this.accessKey=environment.getProperty("chat.bot.aliyuncs.access.key");
    }

    @Override
    public String call(String content) {
        if(openAiRequest==null){
            openAiRequest = new OpenAiRequest();
        }
        MsgElement msgElement = new MsgElement();
        msgElement.setRole("user");
        msgElement.setContent(content);

        openAiRequest.addMsgElement(msgElement);
        return request(openAiRequest);
    }

    @Override
    public String getUri() {
        return environment.getProperty("chat.bot.aliyuncs.http.uri");
    }

    @Override
    public void beforeProcess(@NonNull OpenAiRequest opRequest) {
        if(opRequest.getModel()==null||"".equals(opRequest.getModel())) {
            opRequest.setModel(this.chatModel);
        }
    }

    @Override
    public String buildResponseBody(HttpResponse<String> response) {
        HashMap jsonMap = new Gson().fromJson(response.body(), HashMap.class);
        List<LinkedTreeMap> messlist = (ArrayList<LinkedTreeMap>)jsonMap.get("choices");
        LinkedTreeMap message=(LinkedTreeMap)messlist.get(0).get("message");
        return (String) message.get("content");
    }

    @Override
    public List<HttpHeader> getheaderList() {
        HttpHeader httpHeader = new HttpHeader();
        httpHeader.setName("Authorization");
        httpHeader.setValue("Bearer "+this.accessKey);
        return Arrays.asList(httpHeader);
    }
}
